<?php
# http://projects:8081/cdapp-2kt-api/api/activity_important_load.php
include_once './_portal.php';
include_once './request_sipds.php';

const MIN_TTL = 600 * 1000; # unit: ms
const MAX_TTL = 3600 * 1000; # unit: ms
const PARAM_NAME = 'activityImportantRefreshTime';
const API_NAMES = [
  'importantTaskWebService.findImportantTaskPage(today)',
  'importantTaskWebService.findImportantTaskPage(tomorrow)',
];

$refresh_info = get_param(PARAM_NAME);
$ttl_verify = verify_ttl($refresh_info['tx'], $refresh_info['rx'], MIN_TTL, MAX_TTL);
$info = 'activity_important_load: ' . $ttl_verify['info'];
$status = $ttl_verify['status'];
$time = $ttl_verify['time'];

if ($status > 0) {
  save_param(PARAM_NAME, ['tx' => $time, 'rx' => $refresh_info['rx']]);
  $request_result = refresh_data(API_NAMES);
  $info .= ' ' . $request_result['info'];
  $status = $status * $request_result['status'];
  $time_rx = timestamp();
  save_param(PARAM_NAME, ['tx' => $time, 'rx' => $time_rx]);
}

output([
  'status' => $status,
  'info' => $info,
  'data' => exec_sql("SELECT * FROM `2kt_activity_important`"),
]);

die();

# request content from sipds
function refresh_data($api_names = []) {
  $sql_arr = ["TRUNCATE TABLE `2kt_activity_important`"];
  $result = true;
  for ($i = 0; $i < count($api_names); $i++) {
    $day = $i;
    $api_name = $api_names[$i];
    $response = request_sipds($api_name);
    if ($response['status'] == 0) {
      return [
        'status' => 0,
        'info' => 'Failed to refresh data, sending request failed.',
      ];
    }
    if (!isset($response['data']['CONTENTS']) || $response['data']['CONTENTS'] == null) {
      // return [
      //   'status' => 0,
      //   'info' => 'Failed to refresh data, recived null response.',
      // ];
    } else {
      $sql = "INSERT INTO `2kt_activity_important`(`number`, `flightNumber`, `aircraftType`, `arrivalAirport`, `departureAirport`, `alternateAirport`, `taskGrade`, `status`, `comments`, `ETD`, `ATD`, `ETA`, `ATA`, `day`) VALUES ";
      foreach ($response['data']['CONTENTS'] as $res) {
        $element = [
          'flightNumber' => isset($res['FLIGHTNUM']) ? $res['FLIGHTNUM'] : '',
          'aircraftType' => isset($res['AIRCRAFTTYPE']) ? $res['AIRCRAFTTYPE'] : '',
          'arrivalAirport' => isset($res['ARRAIRPORT']) ? $res['ARRAIRPORT'] : '',
          'departureAirport' => isset($res['DEPAIRPORT']) ? $res['DEPAIRPORT'] : '',
          'alternateAirport' => isset($res['ALTNAIRPORT']) ? $res['ALTNAIRPORT'] : '',
          'taskGrade' => isset($res['TASKGRADE']) ? $res['TASKGRADE'] : -1,
          'status' => isset($res['STATUS']) ? $res['STATUS'] : -1,
          'comments' => isset($res['COMMENTS']) ? $res['COMMENTS'] : '',
          'ETD' => isset($res['ETD']) ? substr($res['ETD'], 0, 10) . ' ' . substr($res['ETD'], 11, 8) : '',
          'ATD' => isset($res['ATD']) ? substr($res['ATD'], 0, 10) . ' ' . substr($res['ATD'], 11, 8) : '',
          'ETA' => isset($res['ETA']) ? substr($res['ETA'], 0, 10) . ' ' . substr($res['ETA'], 11, 8) : '',
          'ATA' => isset($res['ATA']) ? substr($res['ATA'], 0, 10) . ' ' . substr($res['ATA'], 11, 8) : '',
          'day' => $day,
        ];
        $sql .= "(null, '{$element['flightNumber']}', '{$element['aircraftType']}', '{$element['arrivalAirport']}', '{$element['departureAirport']}', '{$element['alternateAirport']}', {$element['taskGrade']}, {$element['status']}, '{$element['comments']}', '{$element['ETD']}', '{$element['ATD']}', '{$element['ETA']}', '{$element['ATA']}', {$element['day']}),";
      }
      $sql = rtrim($sql, ',');
      array_push($sql_arr, $sql);
    }
  }
  $result_arr = exec_sql_array($sql_arr);
  foreach ($result_arr as $r) {
    $result = $result && $r;
  }
  if ($result) {
    return [
      'status' => 1,
      'info' => 'Successed to refresh data.',
    ];
  } else {
    return [
      'status' => 0,
      'info' => 'Failed refresh data, database update filed.',
    ];
  }
}
